package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 异步（从线程池获取子线程）将用户搜索记录存入MongDB集合中
     *
     * @param keyword     关键字
     * @param userId      用户ID
     * @param equipmentId 设备ID
     */
    @Async
    @Override
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {
        //1.判断该用户或者设备是否已经搜索过该记录
        //1.1 构建查询条件Query
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(equipmentId));
        }
        query.addCriteria(Criteria.where("keyword").is(keyword));
        //1.2 根据条件查询MongoDB中数量
        long count = mongoTemplate.count(query, ApUserSearch.class);

        //2.根据返回数量 如果结果为null才进行记录
        if (count == 0) {
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setKeyword(keyword);
            apUserSearch.setEquipmentId(equipmentId);
            apUserSearch.setUserId(userId);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, "apUserSearch");
        }
    }

    /**
     * 获取用户最新前五条搜索记录集合
     *
     * @param dto 查询条件
     * @return 搜索记录集合
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        //1.封装查询MongoDB条件 用户ID或者设备ID，排序，前5条
        Query query = new Query();
        //1.1 设置用户或者设备ID
        User user = UserThreadLocalUtil.get();
        Integer userId = user.getUserId();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //1.2 分页并且根据创建时间倒序
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.DESC, "createdTime");
        query.with(pageable);
        //2.执行查询
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }


    /**
     * 删除用户搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        //1.构建删除条件
        Query query = new Query();
        //1.1 批量删除传入多个搜索记录集合
        List<ApUserSearch> hisList = dto.getHisList();
        if (!CollectionUtils.isEmpty(hisList)) {
            List<String> collect = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
            query.addCriteria(Criteria.where("id").in(collect));
            //2.执行删除文档数据
            mongoTemplate.remove(query, ApUserSearch.class);
        }
        return ResponseResult.okResult();
    }
}
